import React, {useEffect, useState} from 'react';
import {
  Form,
  Input,
  InputNumber,
  Button,
  Select,
  Switch,
  Card,
  message,
  TreeSelect,
} from 'antd';
import styles from "@/pages/sys/oauth/index.less";
import * as service from "@/pages/sys/config/service";
import {queryLayerCategory} from "@/pages/sys/category/service";

const SysOptions = () => {
  const [form] = Form.useForm();
  const [tenantStatus, setTenantStatus] = useState(false);
  const [domainStatus, setDomainStatus] = useState(false);
  const [commentStatus, setCommentStatus] = useState(false);
  const [emailStatus, setEmailStatus] = useState(false);
  const [treeData, setTreeData] = useState([]);

  const reload = async () => {
    const res = await service.fetchSysOptions();
    if (res?.data) {
      form.setFieldsValue(res.data);
      // eslint-disable-next-line camelcase
      const {wldos_system_multitenancy_switch = 'false', wldos_system_multidomain_switch = 'false', wldos_platform_user_register_emailaction = 'false'} = res.data;
      setTenantStatus(wldos_system_multitenancy_switch === 'true');
      setDomainStatus(wldos_system_multidomain_switch === 'true');
      setEmailStatus(wldos_platform_user_register_emailaction === 'true');
    }
  }

  useEffect(async () => {
    await reload();

    const res = await queryLayerCategory();
    if (res?.data) {
      setTreeData(res.data);
    }
  }, []);

  const handleFinish = async () => {
    const values = await form.validateFields();

    const hide = message.loading('正在配置');

    try {
      await service.configOptions(values);
      hide();
      message.success('配置成功').then(() => reload());
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const validateNonRoot = async (rule, value = 0) => {
    const {required = false, root = 0, message: mes = '请输入合适的值'} = rule;
    if (required && value === undefined) {
      return Promise.reject(new Error(mes));
    }
    if (root === value) {
      return Promise.reject(new Error(mes));
    }
    return Promise.resolve();
  };

  const validateNum = async (rule, value = 0) => {
    const {required = false, min = 0, max = 0, message: mes = '请输入合适的值'} = rule;
    if (required && value === undefined) {
      return Promise.reject(new Error(mes));
    }
    if (value > max || value < min) {
      return Promise.reject(new Error(mes));
    }
    return Promise.resolve();
  };

  const tProps = {
    treeData,
    treeDefaultExpandAll: true,
    allowClear: true,
    treeLine: true,
    placeholder: '请选择',
    style: {
      width: '100%',
    },
    showSearch: true,
    treeNodeFilterProp: 'title',
    dropdownStyle: { maxHeight: 400, overflow: 'auto'},
  };

  return (
      <Card className={styles.tabsCard} bordered={false} >
      <Form
        labelCol={{ span: 4, }}
        wrapperCol={{ span: 14, }}
        layout="horizontal"
        form={form}
      >
        <Form.Item
          name="wldos_platform_domain"
          label="平台根域名"
           rules={[
             {
               required: true,
               message: '请输入平台根域名，不能为空，最多120个字符！',
               min: 1,
               max: 120,
             },
           ]}
        >
          <Input placeholder="不带www的顶级域名"/>
        </Form.Item>
        <Form.Item
          name="wldos_req_protocol"
          label="平台请求协议"
          rules={[
            {
              required: true,
              message: '请输入平台请求协议！',
            },
          ]}
        >
          <Select placeholder="请设置请求协议，默认https">
            <Select.Option value="http">http</Select.Option>
            <Select.Option value="https">https</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item name="wldos_system_multitenancy_switch" label="多租户模式">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={tenantStatus} onChange={(e) => setTenantStatus(e)}/>
        </Form.Item>
        <Form.Item name="wldos_system_multidomain_switch" label="多站点模式">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={domainStatus} onChange={(e) => setDomainStatus(e)}/>
        </Form.Item>
        <Form.Item name="wldos_file_store_path" label="文件存储路径">
          <Input placeholder="默认留空对应根目录下store目录" />
        </Form.Item>
        <Form.Item
          name="wldos_platform_adminEmail"
          label="管理员邮箱"
          rules={[
            {
              required: false,
              message: '管理员邮箱，最多120个字符！',
              max: 120,
            },
            {
              type: 'email',
              message: '请输入正确格式邮箱',
            }
          ]}
        >
          <Input placeholder="请输入管理员邮箱"/>
        </Form.Item>
        <Form.Item name="wldos_cms_comment_audit" label="评论审核">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={commentStatus} onChange={(e) => setCommentStatus(e)}/>
        </Form.Item>
        <Form.Item
          name="wldos_cms_defaultTermTypeId"
          label="内容默认分类"
          rules={[
            {
              required: true,
              message: '请选择默认分类！',
            },
            {
              required: true,
              root: 0,
              message: '不能设置为根分类',
              validator: async (rule, value) => validateNonRoot(rule, value),
            }
          ]}
        >
          <TreeSelect {...tProps} />
        </Form.Item>
        <Form.Item
          name="wldos_cms_content_maxLength"
          label="单篇内容最大长度"
          rules={[
            {
              required: true,
              message: '请设置单篇发布最长篇幅！',
            },
            {
              required: true,
              min: 2000,
              max: 53610,
              message: '单个发布字符数上限最多53610，最少2000',
              validator: async (rule, value) => validateNum(rule, value),
            },
          ]}
        >
          <InputNumber />
        </Form.Item>
        <Form.Item
          name="wldos_cms_tag_maxTagNum"
          label="单个发布最多设置几个标签"
          rules={[
            {
              required: true,
              message: '请设置单个发布允许添加的标签个数！',
            },
            {
              required: true,
              min: 1,
              max: 5,
              message: '单个发布最多5个标签',
              validator: async (rule, value) => validateNum(rule, value),
            },
          ]}
        >
          <InputNumber />
        </Form.Item>
        <Form.Item
          name="wldos_cms_tag_tagLength"
          label="标签最长字符数"
          rules={[
            {
              required: true,
              message: '请设置标签最长字符数（每3个字符代表一个汉字）！',
            },
            {
              required: true,
              min: 3,
              max: 30,
              message: '标签字符数3到30位',
              validator: async (rule, value) => validateNum(rule, value),
            },
          ]}
        >
          <InputNumber />
        </Form.Item>
        <Form.Item name="wldos_platform_user_register_emailaction" label="注册是否开启邮箱激活">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={emailStatus} onChange={(e) => setEmailStatus(e)}/>
        </Form.Item>
        {emailStatus && (<><Form.Item
          name="spring_mail_host"
          label="发件服务器(smtp)"
          rules={[
            {
              required: true,
              message: '发件服务器(smtp)，最多60个字符！',
              max: 60,
            },
          ]}
        >
          <Input placeholder="请设置发件服务器(smtp.xx.com)"/>
        </Form.Item>
        <Form.Item
          name="spring_mail_username"
          label="发件用户名"
          rules={[
            {
              required: true,
              message: '发件用户名，最多50个字符！',
              max: 50,
            },
          ]}
        >
          <Input placeholder="请输入发件用户名"/>
        </Form.Item>
        <Form.Item
          name="spring_mail_password"
          label="发件密码"
          rules={[
            {
              required: true,
              message: '发件密码，最多120个字符！',
              max: 120,
            },
          ]}
        >
          <Input placeholder="请输入发件密码"/>
        </Form.Item>
        <Form.Item
          name="wldos_mail_fromMail_addr"
          label="发件邮箱地址"
          rules={[
            {
              required: true,
              message: '发件邮箱地址，最多120个字符！',
              max: 120,
            },
            {
              type: 'email',
              message: '请输入正确格式邮箱',
            }
          ]}
        >
          <Input placeholder="请设置发件邮箱地址"/>
        </Form.Item></>)}
        <Form.Item>
          <Button htmlType="submit" type="primary" onClick={() => handleFinish()}>
            保存配置
          </Button>
        </Form.Item>
      </Form>
      </Card>
  );
};

export default SysOptions;

